/**
 * Created by Dalyn on 2017/3/22.
 * 结算-结算中心
 */
import React from "react";
import {hashHistory} from 'react-router';
import {browserHistory} from 'react-router';
import Relay from "react-relay";
import GetEnBalanceListMutation from "./mutation/GetEnBalanceListMutation"
import Confirm from "../../common/Confirm"
import InputBox from "../../common/InputBox"
import ExamineBomb from "./ExamineBomb"
import InfoCheckBomb from "./InfoCheckBomb";

import ToViewEye from './ToViewEye' //查看弹出框

import SettlementCenter_item from "./SettlementCenter_item"
import "./css/settlement.css";

/*导出组件*/
export default class SettlementCenter extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            listInfo: [],
            /*按钮颜色*/
            wholeFlag: true,
            pendFlag: false,
            alyFlag: false,
            /*当前企业ID*/
            partyBEnid: "",
            /*总共多少条*/
            totalResult: "",

            /*/!*借款金额*!/
            loanMoney: "",
            /!*订单余额*!/
            remainAmount:"",
            /!*结款利息*!/
            loanInterest:"",*/
            orderId:"",
            tranNo:"",
            /*结算金额*/
            amount_s:"",
            /*还款金额*/
            amount_r:"",
            /*本金*/
            principal:"",
            /*利息*/
            interest:"",

            /*每页条数*/
            pageItem: "",
            /*指定页码*/
            pageNum: 1,
            /*指定每页显示条数*/
            pageSize: 10,
            /*0-未还款，1-已还款*/
            status: "2,3,4,5",
            /*操作*/
            _statusText:"",
            /*借款公司名*/
            partyBEnName: "",
            /*申请方*/
            apply:"",
            /*订单编号*/
            order:"",
            /*后台错误提示*/
            hint: "",
            /*操作成功提示*/
            successHint:true,
        };
        /*操作*/
        this._statusText="";
        this.style = {
            confirm: {
                width: '90px',
                height: '28px',
                backgroundColor: "#f7f5f5",
                fontSize: "14px",
                color: "#333333",
                fontFamily: "Microsoft YaHei",
                border:"1px solid #ededed",
                borderRadius: "5px",
                marginLeft: "20px",
                padding:"5px 25px"
            },
            confirm_active: {
                width: '90px',
                height: '30px',
                backgroundColor: "#7abd54",
                fontSize: "14px",
                color: "#fff",
                fontFamily: "Microsoft YaHei",
                borderRadius: "5px",
                marginLeft: "20px",
                padding:"5px 25px"
            },
            company: {
                width: "150px",
                height: "20px",
                borderColor: "#c2df88",
                borderStyle:"solid",
                // marginTop: "15px"
            },
            conPage: {
                width: '50px',
                height: '25px',
                backgroundColor: "#7abd54",
                fontSize: "12px",
                color: "#fff",
                fontFamily: "Microsoft YaHei",
                borderRadius: "3px",
                marginLeft: "10px",
                marginTop: "-4px"
            }
        };
        this.pageNum=1;
    }

    myRelay() {
        if(this.refs.apply){//如果页面初始化完成，校验查询数据
            let apply = this.refs.apply.state.text;
            let order = this.refs.order.state.text;
            let reg_name = /^[a-zA-Z\u4e00-\u9fa5（）]+$/;
            let reg_order = /^\w{1,50}$/g;
            if(apply && !reg_name.test(apply)){
                this.setState({
                    listInfo: [],
                    totalResult: "0",
                    pageItem: "0",
                    balanceMoney: "0.00",
                    sumInterest: "0.00",
                    remainAmount:"0.00",
                    hint: ""
                });
                this.refs.page.value=this.state.pageNum;
                return;
            }else if(order && !reg_order.test(order)){
                this.setState({
                    listInfo: [],
                    totalResult: "0",
                    pageItem: "0",
                    balanceMoney: "0.00",
                    sumInterest: "0.00",
                    remainAmount:"0.00",
                    hint: ""
                });
                this.refs.page.value=this.state.pageNum;
                return;
            }
        }
        /*请求数据*/
        Relay.Store.commitUpdate(
            new GetEnBalanceListMutation({
                orderId:this.state.order,
                partyBEnName:this.state.apply,
                pageNum: this.state.pageNum,
                pageSize: this.state.pageSize,
                status: this.state.status,
            }),
            {
                onFailure: () => {
                    console.log("请求失败")
                },
                onSuccess: (response) => {
                    let data = response.getEnBalanceList.data;
                    // console.log(data)
                    if (data.errorCode === "0") {
                        this.setState({
                            listInfo: data.enterpriseBalanceList,
                            totalResult: data.totalResult,
                            pageItem: data.enterpriseBalanceList.length,
                            balanceMoney: data.balanceMoney,
                            sumInterest: data.sumInterest,
                            remainAmount:data.remainAmount,
                            hint: ""
                        });
                        this.refs.page.value = this.state.pageNum;
                    } else {
                        this.setState({
                            hint: data.value,
                        });
                    }
                }

            }
        );
    }
    componentWillMount() {
        // this.setState({
        //     wholeFlag:true,
        //     pendFlag:false,
        //     alyFlag:false,
        // });
       this.myRelay();
    }
    /*点击操作*/
    bombBox(index,item){
        let status = item.status;
        this.setState({
            orderId:item.orderId,
            statusItem:item.status,
            amount_s:item.remainAmount-item.loanMoney-item.loanInterest,
            principal:item.loanMoney,
            interest:item.loanInterest
        },()=>{
            if(status == "3"){
                /*信息核对*/
                this.refs._infoCheck.handleCancel(this.refs._infoCheck.state.displayflag);
                this.refs._infoCheck.initHit();
            }else if(status == "4" || status == "5" || status == "2"){
                /*查看发票*/
                hashHistory.push({
                    pathname:"/settementCenterEye/",
                    state:{
                        orderId:item.orderId,
                        isResultsView:status
                    }
                })
            }
        });
    }

    /*上传发票成功*/
    examineSuccess(invoiceImg,orderId){
        this.myRelay();
       this.setState({
            successHint:false,
        },()=>{
            let timer = setTimeout(()=>{
                clearTimeout(timer);
                let timer = this.setState({
                    successHint:true,
                })
            },2000);
        });

    }
    /*信息核对成功*/
    infoCheckSuccess(status,tranNo){
        this.myRelay();
        this.setState({
            successHint:false,
        },()=>{
            let timer = setTimeout(()=>{
                clearTimeout(timer);
                let timer = this.setState({
                    successHint:true,
                })
            },2000);
        });
    }
    /*绑定数据*/
    addList() {
        if( null == this.state.listInfo || this.state.listInfo.length == 0){
            return (
                <tr>
                    <td>暂无相关数据</td>
                </tr>
            )
        }else{
            console.log(this.state.listInfo);
            return this.state.listInfo.map((item, index) => {
                return (
                    <SettlementCenter_item ref={index + 'loan_item'} item={item} index={index} key={index + '-'} _bombBox={this.bombBox.bind(this)}/>
                )
            })
        }
    }

    /*全部*/
    whole() {
        this.setState({
            status: "2,3,4,5",
            wholeFlag: true,
            pendFlag: false,
            alyFlag: false,
        }, this.search);
    }

    /*未结算*/
    pending() {
        this.setState({
            status: "2,3,5",
            wholeFlag: false,
            pendFlag: true,
            alyFlag: false,
        }, this.search);
    }

    /*已结算*/
    already() {
        this.setState({
            status: "4",
            wholeFlag: false,
            pendFlag: false,
            alyFlag: true,
        }, this.search);
    }

    /*模糊搜索*/
    search() {
        this.setState({
            apply:this.refs.apply.state.text,
            order:this.refs.order.state.text,
            pageNum: "1",
            pageSize: this.state.pageSize,
            hint:""
        }, this.myRelay);
        this.refs.page.value = this.state.pageNum;
    }

    /*页面表单失去焦点时*/
    bluron(type) {
        switch (type) {
            case "apply":
                this.setState({
                    apply: this.refs.apply.state.text,
                });
                return;
            case "order":
                this.setState({
                    order: this.refs.order.state.text,
                });
                return;
            case "page":{
                let pageNum = this.refs.page.value;

                if (pageNum<1){
                    this.setState({
                        pageNum:1
                    });
                }
                if (pageNum > this.pageTotal()){
                    this.setState({
                        pageNum:this.pageTotal()
                    });
                }
                if(this.refs.page.value == ""){
                    this.setState({
                        pageNum:this.pageNum
                    });
                }
                return;

                /*   this.setState({
                 pageNum: this.refs.page.value == "" ? this.state.pageNum : this.refs.page.value,
                 });
                 return;*/
            }
        }
    }

    /*获取焦点*/
    focuson(type) {
        switch (type) {
            case "apply":
                this.setState({
                    hint: ""
                });
                return;
            case "order":
                this.setState({
                    hint: ""
                });
                return;
        }
    }

    /**
     * 当输入页码时进行校验
     */
    pageNumChange(e){
        let numtest = /^[0-9]*$/;
        let text = e.target.value;
        if (!numtest.test(text)) {
            return;
        }
        this.setState({
            pageNum:text
        });
    }

    /*页码*/
    page() {
        this.bluron();
        this.setState({
            pageNum: this.refs.page.value == "" ? "1" : this.refs.page.value,
        }, this.myRelay);
        this.refs.page.value = this.state.pageNum;
    }

    /*总页数*/
    pageTotal() {
        return Math.ceil(this.state.totalResult / this.state.pageSize)
    }
    /*上一页*/
    leftBtn() {
        let pageNum = this.state.pageNum;
        if (pageNum <= 1) {
            return;
        } else {
            pageNum--;
            this.pageNum = pageNum;
            // this.bluron();
            this.setState({
                pageNum: pageNum,
            }, this.myRelay)
        }
    }

    /*下一页*/
    rightBtn() {
        let pageTotal = this.pageTotal();
        let pageNum = this.state.pageNum;
        if (pageNum >= pageTotal) {
            return;
        } else {
            pageNum++;
            this.pageNum = pageNum;
            this.setState({
                pageNum: pageNum,
            }, this.myRelay)
        }
    }

    render() {
        return (
            <div className="settle_rec" style={{marginTop:10}}>
                {/*<p className="settle_rec_nav1">结算 > <span className="settle_rec_nav2">结算中心</span></p>*/}
                <div className="settle_rec_box">
                    {/*搜索*/}
                    <div className="settle_center_search clear">
                        <div className="settle_center_searchInp">
                            <InputBox titletext={'申请结算方：'} className="people_border-none" space={10} style={this.style.company} defaultvalute="申请结算方"
                                      maxlength={50} ref={'apply'} bluron={this.bluron.bind(this, "apply")}s
                                      focuson={this.focuson.bind(this, "search")}/>
                        </div>
                        <div className="settle_center_searchInp">
                            <InputBox titletext={'订单编号：'} className="people_border-none" space={10} style={this.style.company} defaultvalute="订单编号"
                                      maxlength={22} ref={'order'} bluron={this.bluron.bind(this, "order")}
                                      focuson={this.focuson.bind(this, "search")}/>
                        </div>
                        <div className="settle_center_searchBtn">
                            <Confirm style={this.style.confirm_active} tcontext={'搜索'} touch={this.search.bind(this)}/>
                            <span className="settle_center_searchHint">{this.state.hint}</span>
                        </div>
                    </div>
                    <div className="settle_center_bth-filter">
                        <span className="settle_rec_tab">结算状态：</span>
                        <span style={this.state.wholeFlag ? this.style.confirm_active : this.style.confirm}
                              onClick={this.whole.bind(this)} data-type="btn">全部</span>
                        <span style={this.state.pendFlag ? this.style.confirm_active : this.style.confirm}
                              onClick={this.pending.bind(this)} data-type="btn">未结算</span>
                        <span style={this.state.alyFlag ? this.style.confirm_active : this.style.confirm}
                              onClick={this.already.bind(this)} data-type="btn">已结算</span>
                    </div>
                    <table className="settle_rec_table">
                        <thead>
                            <tr>
                                {
                                    ["订单编号","申请结算方","订单余额（元）","借款金额（元）","利息（元）","申请时间","结算时间","状态","操作"].map((item,index)=>
                                        <th key={`th_${index}`}> {item} </th>
                                    )
                                }
                            </tr>
                        </thead>
                        <tbody>
                            {
                                this.addList()
                            }
                        </tbody>
                    </table>
                    {/*弹框*/}
                   {/* <ExamineBomb ref={"_examine"} partyAEnid={this.state.partyAEnid} _success={this.success.bind(this)}
                             partyBEnid={this.state.partyBEnid} arr_partyBEnid={this.state.arr_partyBEnid} ratio={this.state.ratioItem} dayRate={this.state.dayRateItem}/>*/}
                    <ExamineBomb ref={"_examine"}  _success={this.examineSuccess.bind(this)} _orderId={this.state.orderId} _statusItem={this.state.statusItem}/>
                    <InfoCheckBomb ref={"_infoCheck"}  _success={this.infoCheckSuccess.bind(this)} _amount={this.state.amount_s} _principal={this.state.principal} _interest={this.state.interest} _orderId={this.state.orderId} _statusItem={this.state.statusItem}/>

                    {/*操作成功提示*/}
                    <div className="settle_success_bg" style={this.state.successHint ? {display: 'none'} : {display: 'block'}}></div>
                    {/*分页*/}
                    <div className="settle_page clear">
                        <ol className="settle_page_ol clear">
                            <li className="settle_page_oli1">总计<span>{this.state.totalResult}</span>条</li>
                            <li className="settle_page_oli2">每页<span>{this.state.pageItem}</span>条</li>
                            <li className="settle_page_oli3">
                                共<span>{this.pageTotal()}</span>页
                            </li>
                            <li>第&nbsp;&nbsp;<input type="text" className="settle_page_olinp" ref={"page"} onChange={this.pageNumChange.bind(this)} value={this.state.pageNum}
                                                    onBlur={this.bluron.bind(this, "page")}/>&nbsp;&nbsp;页
                            </li>
                            <li><Confirm tcontext={'确定'} style={this.style.conPage} touch={this.page.bind(this)}
                                         bluron/>
                            </li>
                            <li className="settle_page_olbtn">
                                <i className="settle_page_button settle_page_left"
                                   onClick={this.leftBtn.bind(this)}></i>
                                <i className="settle_page_button settle_page_right"
                                   onClick={this.rightBtn.bind(this)}></i>
                            </li>
                        </ol>
                    </div>
                </div>
            </div>
        )
    }
}
